#include "containers.h"


/* Allocate new data_t on the heap , and return it's refs */
struct data_t *new_data(int __data, struct data_t *__next)
{
	struct data_t *ret;

	ret = (struct data_t *)malloc(sizeof(struct data_t));
	ret->data = __data;
	ret->next = __next;
	return ret;
}

/* Allocate a new queue_t on the heap , and reset it's memory then return */
struct queue_t *init_queue()
{
	struct queue_t *ret;
	ret = (struct queue_t *)malloc(sizeof(struct queue_t));
	memset(ret, 0, sizeof(struct queue_t));

	return ret;
}

void enqueue(struct queue_t *queue, int __data)
{
	// last element points null temporarily
	struct data_t *data = new_data(__data, NULL);

	if (queue->len)
	{
		// if queue is not empty

		// allocate new data ,and point to last element using tail pointer of queue_t
		queue->tail->next = data;
		queue->tail = data;
	}
	else
	{
		// queue is empty

		// both pointers in queue point to the same position(data);
		queue->head = data;
		queue->tail = data;
	}

	queue->len++;
}

int dequeue(struct queue_t *queue)
{
	int ret;
	struct data_t *tmp;

	// is empty queue
	if (!queue->len)
		return CONTAINER_EMPTY;

	// not empty queue
	tmp = queue->head;
	queue->head = tmp->next;
	ret = tmp->data;
	free(tmp);

	queue->len--;

	return ret;
}